import asyncio
import aiomysql
import threading
import time
import json
from .setting import *


#单例模式下的线程池用法
class ConnMysqlSlave():
    _instance = None
    _initialized = False

    def __new__(cls, *args, **kwargs):  #去内存申请地址
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, loop=None):  #可以传入一个指定的永久loop,
        if not self._initialized:
            #创建一个新的事件循环线程
            if loop == None:
                self.newlp = asyncio.new_event_loop()
                t = threading.Thread(target=self.thread_running_loop,
                                     args=(self.newlp, ))
                t.start()
            else:
                self.newlp = loop
            asyncio.run_coroutine_threadsafe(self.pools(), self.newlp)
            print("正在建立线程池")
            time.sleep(0.5)
            self._initialized = True

    def thread_running_loop(self, lp: asyncio.AbstractEventLoop):  #开启loop
        asyncio.set_event_loop(lp)  #在此线程中设置一个新的事件循环,默认情况下事件循环是主线程的
        lp.run_forever()

    async def pools(self):  #开启线程池的coro
        self.pool = await aiomysql.create_pool(host=MYSQL_SLAVE_IP,
                                               port=MYSQL_SLAVE_PROT,
                                               user=MYSQL_SLAVE_USER,
                                               password=MYSQL_SLAVE_PWD,
                                               db=MYSQL_SLAVE_DB,
                                               loop=self.newlp,
                                               autocommit=False)

        print("线程池开启完毕~~~")
